import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    infoList: JSON.parse(localStorage.getItem('List')) || [], // 初始数据
    nextId: 5, // 自动id
    inputValue: '', // 给输入框初始内容,
    changeClass: 'all'
  },
  mutations: {
    // 得到请求的数据
    GETLIST(state, infoList) {
      state.infoList = infoList
    },
    // 添加操作
    addList(state) {
      if (state.inputValue.trim().length <= 0) {
        return alert('文本框不能为空')
      }
      let obj = {
        id: state.nextId,
        info: state.inputValue,
        done: false
      }
      state.inputValue = ''
      state.nextId++
      state.infoList.push(obj)
      // localStorage.setItem('List', JSON.stringify(state.infoList))
    },
    // 输入框改变时监听
    handleInputChange(state, e) {
      state.inputValue = e.target.value
    },
    // 删除子项目，需要参数id
    cleanItem(state, id) {
      if (confirm('确认删除吗')) {
        const i = state.infoList.findIndex(obj => {
          return obj.id == id
        })
        if (i != -1) {
          state.infoList.splice(i, 1)
          // localStorage.setItem('List', JSON.stringify(state.infoList))
        }
      }


    },
    // 复选框选中，需要参数id
    cbStatusChange(state, { e, id }) {
      state.infoList.some(obj => {
        if (obj.id == id) {
          obj.done = e.target.checked
        }
      })
      // localStorage.setItem('List', JSON.stringify(state.infoList))
    },
    // 清除已完成
    clearDone(state) {
      state.infoList = state.infoList.filter(obj => !obj.done)
      // localStorage.setItem('List', JSON.stringify(state.infoList))
    },
    // 点击已完成、未完成、全部
    changeList(state, key) {
      state.changeClass = key
    }
  },
  actions: {
    // 获取异步请求,到mutation中
    getList(context) {
      axios.get('/list.json').then(({ data }) => {
        if (JSON.parse(localStorage.getItem('List'))) {
          data = JSON.parse(localStorage.getItem('List'))
        }
        context.commit('GETLIST', data)
      })
    }
  },
  modules: {
  },
  getters: {
    // 未完成剩余条数
    unDoneItem(state) {
      return state.infoList.filter(obj => obj.done == false).length
    },
    // // 点击已完成、未完成、全部的list
    infoList(state) {
      if (state.changeClass == 'all') {
        return state.infoList
      }
      if (state.changeClass == 'unDone') {
        return state.infoList.filter(obj => !obj.done)
      }
      if (state.changeClass == 'Done') {
        return state.infoList.filter(obj => obj.done)
      }
      return state.infoList
    }
  }
})
